package com.seadragon.app.ksr.dao.jpa;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.seadragon.app.ksr.dao.BusinessDao;
import com.seadragon.app.ksr.model.Business;

@Repository("businessDao")
public class BusinessDaoJpaImpl extends AbstractJpaDao implements BusinessDao {
	private static Logger logger = LoggerFactory.getLogger(BusinessDaoJpaImpl.class);

	@Override
	public void save(Business business) {
		logger.debug("Entering ... ");
		entityManager.persist(business);
		logger.debug("Exiting ... ");
	}

	@Override
	public Business findById(long id) {
		return entityManager.find(Business.class, id);
	}

	@Override
	public Business findByEmail(String email) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Business> cq = cb.createQuery(Business.class);
		Root<Business> root = cq.from(Business.class);
		cq.select(root);
		cq.where(cb.equal(root.get("emailAddress"), email));
		Business business = entityManager.createQuery(cq).getSingleResult();
		if(business.getCategories() != null){
			business.getCategories().size();
		}
		if(business.getOffices() != null){
			business.getOffices().size();
		}
		return business;
	}

	@Override
	public Business update(Business business) {
		return entityManager.merge(business);
	}

	@Override
	public List<Business> findAll(int offset, int pageSize) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<Business> cq = cb.createQuery(Business.class);
		Root<Business> root = cq.from(Business.class);
		cq.select(root);
		TypedQuery<Business> tq = entityManager.createQuery(cq);
		tq.setFirstResult(offset);
		tq.setMaxResults(pageSize);
		return tq.getResultList();
	}

}
